package com.the_ring.chapter12.fragment;

import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Bundle;

import androidx.fragment.app.Fragment;

import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;

import com.the_ring.chapter12.R;

import java.io.FileNotFoundException;

/**
 * A simple {@link Fragment} subclass.
 * Use the {@link PictureFragment#newInstance} factory method to
 * create an instance of this fragment.
 */
public class PictureFragment extends Fragment {

    private static final String TAG = "PictureFragment";

    private static final String PAGE = "page";
    private static final String PATH = "path";


    private int page;
    private String picPath;
    private Bitmap bitmap;

    public PictureFragment() {
        // Required empty public constructor
    }

    public static PictureFragment newInstance(int page, String picturePath) {
        PictureFragment fragment = new PictureFragment();
        Bundle args = new Bundle();
        args.putInt(PAGE, page);
        args.putString(PATH, picturePath);
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (getArguments() != null) {
            page = getArguments().getInt(PAGE);
            picPath = getArguments().getString(PATH);
            try {
                bitmap = BitmapFactory.decodeStream(getContext().getContentResolver().openInputStream(Uri.parse(picPath)));
            } catch (FileNotFoundException e) {
                Log.e(TAG, e.getMessage());
            }
        }
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        View view = inflater.inflate(R.layout.fragment_picture, container, false);
        if (bitmap != null) {
            ((ImageView) view.findViewById(R.id.iv_picture)).setImageBitmap(bitmap);
        }
        return view;
    }
}